package _17_剑指Offer;

public class _04_剑指Offer二维数组中的查找 {

    public static void main(String[] args) {

        _04_剑指Offer二维数组中的查找 v = new _04_剑指Offer二维数组中的查找();

        int[][] ins = new int[][]{
                {1, 4, 7, 11, 15},
                {2, 5, 8, 12, 19},
                {3, 6, 9, 16, 22},
                {10, 13, 14, 17, 24},
                {18, 21, 23, 26, 30}
        };

        System.out.println(v.findNumberIn2DArray(ins, 20));

    }

    // 从有上角开始查找
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if (matrix.length == 0 || matrix[0].length == 0) return false;

        int row = 0;
        int col = matrix[0].length - 1;
        while (row < matrix.length && col >= 0) {
            int cur = matrix[row][col];
            if (cur == target) return true;
            else if (cur < target) {
                col--;
            } else {
                row++;
            }
        }
        return false;
    }

    // 首先，根据二分定位到哪一行，然后在定位到哪一行的那一列
    public boolean findNumberIn2DArray1(int[][] matrix, int target) {
        if (matrix.length == 0 || matrix[0].length == 0) return false;

        int col = matrix[0].length;
        // 查找元素介于那行
        for (int[] ints : matrix) {
            if (ints[0] > target || ints[col - 1] < target) continue;

            // 根据二分定位到那一列
            int beginCol = 0;
            int endCol = col - 1;
            while (beginCol <= endCol) {
                int midCol = beginCol + endCol >> 1;
                if (ints[midCol] > target) {
                    endCol = midCol - 1;
                } else if (ints[midCol] < target) {
                    beginCol = midCol + 1;
                } else {
                    return true;
                }
            }
        }

        return false;
    }

}
